package by.ostrovsky.webhousingsystem.bean.user;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

import by.ostrovsky.webhousingsystem.bean.user.form.UserRequestBean;
import by.ostrovsky.webhousingsystem.constants.Constants;
import by.ostrovsky.webhousingsystem.controller.IUserController;
import by.ostrovsky.webhousingsystem.controller.userrequest.SendRequestController;
import by.ostrovsky.webhousingsystem.hibernate.entity.Account;
import by.ostrovsky.webhousingsystem.hibernate.entity.UserRequest;

@SuppressWarnings("serial")
public class UserRequestAction extends UserRequestBean{
	private static Logger logger = Logger.getLogger(UserRequestAction.class);

	public String execute() {
		IUserController<UserRequest, Boolean> sendController = new SendRequestController();
		try {
			Account acc = new Account();
			acc.setId((String) sessionMap.get(Constants.USERLOGIN));

			UserRequest userRequest = new UserRequest();
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date date = null;
			Date now = new Date();
			if (getDeadline() != "")
				date = dateFormat.parse(getDeadline());
			userRequest.setDeadline(date);
			userRequest.setAccount(acc);
			userRequest.setPhone(getPhone());
			userRequest.setWork(getWork());
			userRequest.setAddinfo(getAdditionalUserInfo());
			userRequest.setRegdate(now);
			userRequest.setAccepted(false);

			if (sendController.send(userRequest)) {
				logger.info(Constants.REQUEST_SENT);
				sessionMap.remove("requestBean");
				return Constants.SUCCESS;
			}

			logger.error(Constants.REQUEST_NOT_SENT);
			return Constants.FAILURE;
		} catch (Exception e) {
			return Constants.FATAL;
		}
	}
}
